//服务列表
//1-地图服务
let url = "http://localhost:8090/iserver/services/map-HHRes/rest/maps/%E9%BB%84%E6%B2%B3%E4%B8%AD%E4%B8%8B%E6%B8%B8%E5%9F%8E%E5%B8%82%E7%BE%A4";
//2-数据服务
let dataUrl = "http://localhost:8090/iserver/services/data-HHRes/rest/data";
let map,//地图
  indexThemeLayer,//因子分析结果的专题图层
  markers = [],//闪烁点容器
  pulseIcon = L.icon.pulse({
    iconSize: [12, 12],
    color: '#2f8'
  }),//闪烁点样式
  resultLayer;//结果图层

//初始化地图服务
function initMap() {
  map = L.map('map', {
    center: [34.86, 116.67],
    zoom: 7
  });

  //  鼠标滑过地图事件
  //  map.on("mousemove", function (e) {
  //     infowinPosition = e.layerPoint;
  //     console.log(infowinPosition);
  //   });

  L.supermap.tiledMapLayer(url, { noWrap: true }).addTo(map); // 添加图层
  //添加闪烁点
  loadPulse(map, markers);
  //初始化图表信息
  initCharts(2018, "人均GDP/万元", "中原↑-山东↓城市群基尼系数");
}

function loadPulse(map, markers) {
  let geoQueryRes = getCityGeoLocations().responseJSON;
  // console.log(geoQueryRes);
  for (var i = 0; i < geoQueryRes.length; i++) {
    markers.push(L.marker(L.latLng(geoQueryRes[i].pointY, geoQueryRes[i].pointX), {
      icon: pulseIcon
    }));
  }
  //添加标记到地图中
  resultLayer = L.featureGroup(markers).addTo(map);
  //为标记图层注册点击事件
  resultLayer.on('mouseover', function (layer) {
    //获取目标点的经纬度信息
    let lat=layer.latlng.lat,
      lng=layer.latlng.lng;
      let latlngInfo={
        'lat':lat,
        'lng':lng
      };
    //获取当前选中的年份
    let year=$("#yearSelect").find("option:selected").text();
    //后台向数据库发起数据请求
    let cityBasicInfo=getCityInfoByLatLng(year,latlngInfo).responseJSON;
    //组件html模板
    let popUpTemplate='<table width="150px" border="1px" cellspacing="0px" cellpadding="3px" style="font-size: 12px;text-align: center;"><tr><td >城市名</td><td width="80px">'+cityBasicInfo[0].cityName+'</td></tr><tr><td>经纬度</td><td>'+(cityBasicInfo[0].pointX,cityBasicInfo[0].pointY)+'</td></tr><tr><td>隶属</td><td>'+cityBasicInfo[0].cityQeueu+'</td></tr><tr><td>省份</td><td>'+cityBasicInfo[0].province+'</td></tr><tr><td>得分[1~10]</td><td>'+cityBasicInfo[0]["s"+year.toString()]+'</td></tr></table>'
    // console.log(cityBasicInfo[0])
    //绑定popup事件
    layer.layer.bindPopup(popUpTemplate);
  });
}

function getCityInfoByLatLng(year,latlngInfo){
  return $.ajax({
    async:false,
    url:"/index/cityBasicInfo.json",
    data:{
      key:"key",
      value:year,
      latLng:latlngInfo,
      sqlQuery:"SELECT citybasicinfo.cityName,citybasicinfo.cityQeueu,citybasicinfo.province,citybasicinfo.pointY,citybasicinfo.pointX,totalscore.s"+year.toString()+" FROM citybasicinfo,totalscore WHERE citybasicinfo.pointX="+latlngInfo.lng.toString()+" and citybasicinfo.pointY="+latlngInfo.lat.toString()+" AND citybasicinfo.cityName=totalscore.cityName"
    },
    type:"GET",
    success:function(result,status,xhr){
      return result;
    }
  });
}



//初始化图表信息
function initCharts(year, chartTitle1, chartTitle2) {
  //1-初始化左边的图表
  let queryRes = getPerGDPInfoByYear(year).responseJSON;//获取结果中的JSON对象
  //数组对象排序
  bubbleJson(queryRes, "perGDP");
  //遍历JSON数组，获取城市名和人均GDP值
  let cityNameArr = new Array(),
    perGDPArr = new Array();
  for (var i = 0; i < queryRes.length; i++) {
    cityNameArr.push(queryRes[i].cityName);
    perGDPArr.push(queryRes[i].perGDP);
  }
  //将信息传递给echarts图表
  initLeftChart(year, chartTitle1, cityNameArr, perGDPArr, "万元");
  //2-初始化右边的图表
  let queryRes_2 = getCityQeueuInfo(2018).responseJSON;
  //将城市群进行分类处理
  let classRes = classCityQeueu(queryRes_2);
  //构造数据集
  let cQeueuSet=constructCitySet(classRes.CQeueu,2018)
  ,sdQeueuSet=constructCitySet(classRes.SDQeueu,2018);
  //将参数传递给图表
  initRightChart_CompScore(cQeueuSet,sdQeueuSet,'2018');
}

function constructCitySet(CitySet,year){
  let dataSet=[];
  for(var i=0;i<CitySet.length;i++){
    dataSet.push(new Array(
      CitySet[i].pointX,//经度
      CitySet[i].pointY,//纬度
      CitySet[i]['s'+year.toString()],//总得分
      CitySet[i].cityName//城市名
    ));
  }
  return dataSet;
}



//年份修改的触发事件
function chageYear() {
  //1-获取更新后的年份
  let val = $("#yearSelect").find("option:selected").text();
  //2-获取当前指标
  console.log(val);
}



function getPerGDPInfoByYear(year) {
  //ajax发起请求
  return $.ajax({
    async: false,//非异步请求，为了获取结果中的JSON对象
    url: "/index/allCityPerGDP.json",
    type: "GET",
    data: {
      key: "key",
      value: year,
      sqlQuery: "SELECT cityName,perGDP FROM year_" + year.toString()
    },
    success: function (result, status, xhr) {
      return result;
    }
  });
}

function getCityQeueuInfo(year) {
  //发起ajax同步请求
  return $.ajax({
    async: false,//非异步请求，为了获取结果中的JSON对象
    url: "/index/CityTotalScoreInfo.json",
    type: "GET",
    data:{
      key:"key",
      value:year,
      sqlQuery:"SELECT citybasicinfo.cityName,citybasicinfo.pointX,citybasicinfo.pointY,citybasicinfo.cityQeueu,totalscore.s"+year.toString() +" FROM citybasicinfo,totalscore WHERE citybasicinfo.cityName=totalscore.cityName"
    },
    success: function (result, status, xhr) {
      return result;
    }
  });
}



//SQL查询
function sqlQueryByCityName(fieldName, filedVal, map) {
  //构造sql查询参数
  let attributeFiltersql = fieldName + "\tlike '%" + filedVal + "%'";
  // 指定SQL查询服务参数
  var sqlParam = new SuperMap.GetFeaturesBySQLParameters({
    queryParameter: {
      name: "HHPro:城市面",
      attributeFilter: attributeFiltersql
    },
    datasetNames: ["HHPro:城市面"]
  });
  //执行查询
  L.supermap.featureService(dataUrl).getFeaturesBySQL(sqlParam, function (serviceResult) {
    //获取并判断查询结果中的要素数量
    if (serviceResult.result.features.features.length == 0) {
      window.alert("查询结果为空!");
      return false;
    }
    //跳转图层
    let lat = serviceResult.result.features.features[0].properties.CENTROID_X,
      lng = serviceResult.result.features.features[0].properties.CENTROID_Y;
    map.flyTo(L.latLng(lng, lat));
    //高亮显示
    L.geoJSON(L.Util.transform(serviceResult.result.features, L.CRS.EPSG3857, L.CRS.EPSG4326)).bindPopup(function (layer) {
      // console.log(layer)
      let info = layer.feature.properties;
      //构造城市对象
      let cityObj = {
        cityName: info.NAME99,
        cityQeueu: info.隶属,
        provinceName: info.省份,
        ceterX: info.CENTROID_X,
        ceterY: info.CENTROID_Y,
        totalArea: info.SHAPE_AREA / 1000000
      };
      let queryResult = queryByCityName(cityObj.cityName);
      //解析返回值中的JSON内容
      let jsonInfo = queryResult.responseJSON[0];
      //为JSON对象添加新属性
      cityObj['jsonInfo'] = jsonInfo;
      // console.log(cityObj['jsonInfo']);
      return getTableTemplate(cityObj)
    }).addTo(map);
  }), {
    resultFormat: "GEOJSON"
  };
}

function getTableTemplate(cityObj) {
  let attributeArr = new Array();//字段名
  let valueArr = new Array();//字段值
  let totalScore = 0;
  for (x in cityObj['jsonInfo']) {
    if (x === "cityName")
      continue;
    attributeArr.push(x);
    totalScore += cityObj.jsonInfo[x];
    valueArr.push(cityObj.jsonInfo[x])
  }
  //获取方差值
  let variance = getVariance(cityObj);
  let tableTemplate = '<table border="1px" style="background-color: bisque;border: solid aquamarine 1px;border-spacing: 0;text-align: center;" cellpadding="5px"><tr><td style="font-weight: 700;" width="120px">城市</td><td width="150px">' + cityObj.cityName + '</td></tr><tr><td style="font-weight: 700;">省份</td><td>' + cityObj.provinceName + '</td></tr><tr><td style="font-weight: 700;">城市群</td><td>' + cityObj.cityQeueu + '</td></tr><tr><td style="font-weight: 700;">占地面积/km²</td><td>' + cityObj.totalArea + '</td></tr> <tr><td style="font-weight: 700;">发展稳定度(-->0)</td><td>' + variance + '</td></tr></table>';
  return tableTemplate;
}

function queryByCityName(cityName) {
  return $.ajax({
    async: false,//非异步请求
    data: {
      key: 'key',
      value: cityName
    },
    url: "/index/getTotalScore.json",//请求地址
    type: "GET",//请求类型
    success: function (result, status, xhr)//对请求结果的处理
    {
      return result;
    }
  });
}




//按钮事件
//搜索城市
function showSearchInput() {
  $("#searchInput").css("display", "table");//显示元素
}
function hideSearchInput() {
  setTimeout(function () {
    // window.alert( $("#inputText").val());
    if ($("#inputText").val().length == 0) {
      $("#searchInput").css("display", "none");//5秒后自动隐藏元素 
    } else {
      return;
    }
  }, 3000)
}
//切换显示/隐藏状态
function noViewSearchInput() {
  if ($("#searchInput").css("display") === "none") {
    showSearchInput();
  } else {
    $("#searchInput").css("display", "none");
  }
}

function searchCity() {
  // 获取输入
  let inputVal = $("#inputText").val();
  if (inputVal.length == 0) {
    window.alert('请输入有效的城市名');
    return false;
  }
  //执行查询
  sqlQueryByCityName("NAME99", inputVal, map);

}

//全局显示
function fullExtent() {
  map.setView(L.latLng(34.86, 116.67), 7, {});
}
//切换区域
function changeArea() {
  map.flyTo(L.latLng(34.86, 116.67));//定位到中心
}

//显示年份选择控件
function showYearSelect() {
  $("#yearSelect").css("display", "inline-block");//显示元素
}

function hideYearSelect() {
  setTimeout(function () {
    $("#yearSelect").css("display", "none");//7秒后自动隐藏元素 
  }, 7000);
}


function refreshMap() {
  //刷新当前页面
  location.reload();
}

function getComScore() {
  //获取年份条件
  let year = $("#yearSelect").find("option:selected").text();
  //发起请求
  $.ajax({
    async: true,//发起异步请求
    url: "/index/comScore.json",
    type: "GET",
    data: {
      key: "key",
      value: year,
      sqlQuery: 'SELECT cityName,totalscore.s' + year.toString() + ' FROM totalscore'
    },
    success: function (result, status, xhr) {
      //冒泡排序
      let sortedResObj = bubbleJson(result, "s" + year.toString());
      // //遍历JSON数组，获取城市名和总GDP
      let cityNameArr = new Array(),
        perSaveMoneyArr = new Array();
      for (var i = 0; i < sortedResObj.length; i++) {
        cityNameArr.push(sortedResObj[i].cityName);
        perSaveMoneyArr.push(sortedResObj[i]["s" + year.toString()]);
      }
      //将参数传递给左边的图表
      initLeftChart(year, "综合得分[0-10]", cityNameArr, perSaveMoneyArr, "分");
      //打印JSon数组
      // console.log(sortedResObj);
      // let geoQueryRes = getCityGeoLocations().responseJSON;
      // var geoCoordMap = {};//存储地理坐标值的JSON对象
      // for (var i = 0; i < geoQueryRes.length; i++) {
      //   geoCoordMap[geoQueryRes[i].cityName] = [geoQueryRes[i].pointX, geoQueryRes[i].pointY];
      // }
      // //声明数据处理方法
      // var convertData = function (data) {
      //   var res = [];
      //   for (var i = 0; i < data.length; i++) {
      //     var geoCoord = geoCoordMap[data[i].cityName];
      //     if (geoCoord) {
      //       res.push({
      //         name: data[i].cityName,
      //         value: geoCoord.concat(data[i]["s" + year.toString()])
      //       });
      //     }
      //   }
      //   return res;
      // };
      // //设置图表样式
      // let option = {
      //   title: {
      //     text: "因子分析-城市发展水平综合得分",
      //     subtext: 'data from 统计年鉴',
      //     // sublink: 'http://www.pm25.in',
      //     left: 'center'
      //   },
      //   tooltip: {
      //     trigger: 'item'
      //   },
      //   legend: {
      //     orient: 'vertical',
      //     y: 'bottom',
      //     x: 'right',
      //     data: ['pm2.5'],
      //     textStyle: {
      //       color: '#fff'
      //     }
      //   },
      //   series: [
      //     {
      //       name: 'pm2.5',
      //       type: 'scatter',
      //       coordinateSystem: 'leaflet',
      //       data: convertData(sortedResObj),////将地理坐标值和原始等级值封装到一起
      //       symbolSize: function (val) {
      //         return val[2] / 10;
      //       },
      //       label: {
      //         normal: {
      //           formatter: '{b}',
      //           position: 'right',
      //           show: false
      //         },
      //         emphasis: {
      //           show: true
      //         }
      //       },
      //       itemStyle: {
      //         normal: {
      //           color: '#ddb926'
      //         }
      //       }
      //     },
      //     {
      //       name: 'Top 5',
      //       type: 'effectScatter',
      //       coordinateSystem: 'leaflet',
      //       data: convertData(sortedResObj.sort(function (a, b) {
      //         return b.value - a.value;
      //       }).slice(0, 6)),
      //       symbolSize: function (val) {
      //         return val[2] / 10;
      //       },
      //       showEffectOn: 'render',
      //       rippleEffect: {
      //         brushType: 'stroke'
      //       },
      //       hoverAnimation: true,
      //       label: {
      //         normal: {
      //           formatter: '{b}',
      //           position: 'right',
      //           show: true,
      //           color: '#ffa022'
      //         }
      //       },
      //       itemStyle: {
      //         normal: {
      //           color: '#ffa022',
      //           shadowBlur: 10,
      //           shadowColor: '#333'
      //         }
      //       },
      //       zlevel: 20000000
      //     }
      //   ]
      // };
      // //添加图标到地图上
      // L.supermap.echartsLayer(option).addTo(map);
    }
  });

}


function getCityGeoLocations() {
  //从数据库中获取城市的经纬度坐标值
  return $.ajax({
    async: false,
    url: "/index/CityGeoLocations.json",
    data: {
      key: "key",
      sqlQuery: "SELECT cityName,pointX,pointY FROM citybasicinfo"
    },
    type: "GET",
    success: function (result, status, xhr) {
      return result;
    }
  });
}





